package com.mallcai.bigdata.ladon.service.report.impl.handler;

import com.mallcai.bigdata.ladon.client.vo.ReportColumnVO;
import com.mallcai.bigdata.ladon.client.vo.ReportDataVO;
import com.mallcai.bigdata.ladon.datasource.RunInfoResult;
import com.mallcai.bigdata.ladon.dpl.vo.DataType;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryConstants;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-20 08:37
 */
@Service
@Slf4j
@Order(2540)
public class ProcessStaticReportHandler extends AbstractReportQueryPreHandler {

    @Override
    public void preInternal(ReportQueryContext context) {
        boolean isStaticReport = context.getInnerParam(ReportQueryConstants.KEY_IS_STATIC_REPORT);
        if (isStaticReport){
            String sql = context.getSql();
            context.setResult(new RunInfoResult<>(createReportDataVO(sql), null, sql, 0));
        }
    }

    private ReportDataVO createReportDataVO(String sql) {
        List<Map<String,Object>> rowList = new ArrayList<>();
        List<ReportColumnVO> columnVoList = new ArrayList<>();
        String[] rows = sql.split("\\n");
        int rowSize = 0;
        for (int i = 0; i < rows.length; i++) {
            String row = rows[i];
            if (StringUtils.isNotEmpty(row)){
                rowSize++;
                Map<String,Object> rowObj = new HashMap<>();
                String[] cols = row.trim().split(",");
                for (int j = 0; j < cols.length; j++) {
                    String columnName = String.format("%s%d","column",j+1);
                    rowObj.put(columnName, cols[j]);
                    if (rowSize == 1){
                        ReportColumnVO reportColumnVO = new ReportColumnVO();
                        reportColumnVO.setName(columnName);
                        reportColumnVO.setShowName(columnName);
                        reportColumnVO.setDataType(DataType.STRING.getCode());
                        columnVoList.add(reportColumnVO);
                    }
                }
                rowList.add(rowObj);
            }
        }
        return new ReportDataVO(columnVoList,rowList);
    }


}
